var express = require('express');
var router = express.Router();
var db = require('../config/sq')

/* 查询用户列表. */
router.get('/list', async (req, res, next) => {
  const val=req.query;
  let pageNo=Number(val?.pageNo)
  let pageSize=Number(val?.pageSize)
  const maxNum=(pageNo-1)*pageSize
  const listSql =`select * from users limit ?, ?`
  const countSql = `select count (1) from users`
  const [rows]=await db.query(listSql,[maxNum,pageSize]);
  const [[count]]= await db.query(countSql)
  const totla=count['count (1)']
  const data={
    list:rows,
    totla
  }
  if(rows.length>0){
    res.send({data:data,msg:'成功',code:'0'})
  }else{
    res.send({data:false,msg:'失败',code:'1'})
  }
});
/* 新增用户 */
router.post('/add', async (req, res, next) => {
  const val=req.body;
  const userName = val.userName;
  const passWord = '123456';
  const age = val.age;
  const address = val.address;
  const birthday = val.birthday;
  const gender = val.gender;
  const loginSql =`select * from users where name= ? `
  const addSql = `INSERT INTO users (name, gender,password,age,address,birthday) VALUES (?,?,?,?,?,?)`
  const [rows]=await db.query(loginSql,userName);
  if(rows.length>0){
    res.send({data:false,msg:'账号已存在无法添加',code:'1'})
  }else{
    const [ResultSetHeader] = await db.query(addSql,[userName,gender,passWord,age,address,birthday])
    if(ResultSetHeader.affectedRows>0){
      res.send({data:true,msg:'成功',code:'0'})
    }else{
      res.send({data:false,msg:'失败',code:'1',token:null})
    }
  }
});

/* 查询用户列表. */
router.get('/queryUser', async (req, res, next) => {
  const id=req.query.id
  const listSql =`select * from users where id = ?`
  const [rows]=await db.query(listSql,id);
  if(rows.length>0){
    res.send({data:rows[0],msg:'成功',code:'0'})
  }else{
    res.send({data:false,msg:'失败',code:'1'})
  }
});

/* 修改用户信息. */
router.post('/updateUser', async (req, res, next) => {
  const val=req.body;
  const {id,userName,age,address,birthday,gender}=val
  const sql = `UPDATE users SET name = ?, gender = ?, age= ?, address = ?, birthday = ? WHERE id = ?`
  const [rows]=await db.query(sql,[userName,gender,age,address,birthday,id]);
  if(rows.changedRows>0){
    res.send({data:true,msg:'成功',code:'0'})
  }else{
    res.send({data:false,msg:'失败',code:'1',token:null})
  }
});

/* 删除用户. */
router.post('/deleteUser', async (req, res, next) => {
  const val=req.body;
  const {id}=val
  const sql = `DELETE FROM users WHERE id = ?`
  const [rows]=await db.query(sql,id);
  if(rows.affectedRows>0){
    res.send({data:true,msg:'成功',code:'0'})
  }else{
    res.send({data:false,msg:'失败',code:'1',token:null})
  }
});

module.exports = router;
